<?php

namespace Winter\Blog\Controllers;

use Backend\Classes\Controller;
use BackendMenu;
use Flash;
use Lang;
use Winter\Blog\Models\Post;
use RainLab\Blog\Models\Category;

class Posts extends Controller
{
    public $implement = [
        \Backend\Behaviors\FormController::class,
        \Backend\Behaviors\ListController::class,
        \Backend\Behaviors\ImportExportController::class
    ];

    public $requiredPermissions = ['winter.blog.access_other_posts', 'winter.blog.access_posts'];

    public function __construct()
    {
        parent::__construct();

        BackendMenu::setContext('Winter.Blog', 'blog', 'posts');
    }

    public function index()
    {
        $this->vars['postsTotal'] = Post::count();
        $this->vars['postsPublished'] = Post::isPublished()->count();
        $this->vars['postsDrafts'] = $this->vars['postsTotal'] - $this->vars['postsPublished'];

        $this->asExtension('ListController')->index();
    }

    public function create()
    {
        BackendMenu::setContextSideMenu('new_post');

        $this->bodyClass = 'compact-container';
        $this->addCss('/plugins/winter/blog/assets/css/winter.blog-preview.css');
        $this->addJs('/plugins/winter/blog/assets/js/post-form.js');

        $result =  $this->asExtension('FormController')->create();

        return $result;
    }

    public function update($recordId = null)
    {
        $this->bodyClass = 'compact-container';
        $this->addCss('/plugins/winter/blog/assets/css/winter.blog-preview.css');
        $this->addJs('/plugins/winter/blog/assets/js/post-form.js');

        $result =  $this->asExtension('FormController')->update($recordId);

        return $result;
    }

    public function export()
    {
        $this->addCss('/plugins/winter/blog/assets/css/winter.blog-export.css');

        return $this->asExtension('ImportExportController')->export();
    }

    public function listExtendQuery($query)
    {
        if (!$this->user->hasAnyAccess(['winter.blog.access_other_posts'])) {
            $query->where('user_id', $this->user->id);
        }
    }

    public function formExtendQuery($query)
    {
        if (!$this->user->hasAnyAccess(['winter.blog.access_other_posts'])) {
            $query->where('user_id', $this->user->id);
        }
    }

    public function formExtendModel($model)
    {
        if ($model->exists && !empty($model->slug) && $model->preview_page) {
            $model->setUrl($model->preview_page, (new \Cms\Classes\Controller()));
        }
    }

    public function formExtendFieldsBefore($widget)
    {
        if (!$model = $widget->model) {
            return;
        }

        // @TODO: This shouldn't engage when the translate plugin is present but disabled
        // Fix can be more restrictive checks here or finishing changes to the class loader so that
        // disabled plugins cannot even have their classes loaded.
        if ($model instanceof Post && $model->isClassExtendedWith('Winter.Translate.Behaviors.TranslatableModel')) {
            $widget->tabs['fields']['content']['type'] = 'Winter\Blog\FormWidgets\MLBlogMarkdown';
        }
    }

    public function index_onDelete()
    {
        if (($checkedIds = post('checked')) && is_array($checkedIds) && count($checkedIds)) {

            foreach ($checkedIds as $postId) {
                if ((!$post = Post::find($postId)) || !$post->canEdit($this->user)) {
                    continue;
                }

                $post->delete();
            }

            Flash::success(Lang::get('winter.blog::lang.post.delete_success'));
        }

        return $this->listRefresh();
    }

    /**
     * {@inheritDoc}
     */
    public function listInjectRowClass($record, $definition = null)
    {
        if (!$record->published) {
            return 'safe disabled';
        }
    }

    public function formBeforeCreate($model)
    {
        $model->user_id = $this->user->id;
    }

    public function onRefreshPreview()
    {
        $data = post('Post');

        $previewHtml = Post::formatHtml($data['content'], true);

        return [
            'preview' => $previewHtml
        ];
    }

    public function formAfterSave($model)
    {
        $this->syncPostsCache();
    }

    /**
     * Called after the creation form is saved.
     * @param \Winter\Storm\Database\Model|\Winter\Storm\Halcyon\Model
     */
    public function formAfterCreate($model)
    {

        $this->syncPostsCache();
    }

    //生成文字缓存

    public function hasInCategory($category, $categories) {
        foreach ($categories as $item) {
            $result = $this->checkHasInArray($category, $item['id']);
            if ($result) {
                return $result;
            }
        }
        return false;
    }

    public function checkHasInArray($category, $categoryId) {
        if ($categoryId == $category['id']) {
            return true;
        }

        $childs = $category['children'];
        if (!empty($childs)) {
            foreach ($childs as $child) {
                $result = $this->checkHasInArray($child, $categoryId);
                if ($result) {
                    return true;
                }
            }
            
        }

        return false;
    }

    public function syncPostsCache() {
        $allPosts = Post::get()->all();

        $cacheFile = storage_path().'/home_post.cache';

        $filterPosts = array();
        foreach ($allPosts as $allPost) {
            $categories = $allPost['categories'];

            $filterPosts[] = array(
                "id" => $allPost['id'],
                "user_id" => $allPost['user_id'],
                "slug" => $allPost['slug'],
                "title" => $allPost['title'],
                "excerpt" => $allPost['excerpt'],
                "created_at" => $allPost['created_at'],
                "published"=>$allPost['published'],
                "updated_at"=> $allPost['updated_at'],
                "categories"=>$categories,
                "featured_images"=>$allPost['featured_images']
            );
        }
        $categoryPosts = array();
        $rootCategories = Category::withCount('posts')
            ->where('parent_id','=',  NULL)
            ->get()->all();

        foreach ($rootCategories as $rootCategorie) {
            $id = $rootCategorie['id'];
            if (!isset($categoryPosts[$id])) {
                $categoryPosts[$id] = array();
            }
            foreach ($filterPosts as $post) {
                if ($this->hasInCategory($rootCategorie, $post['categories'])) {
                    $categoryPosts[$id][] = $post;
                }
            }
        }
        
        file_put_contents($cacheFile, json_encode($categoryPosts));
    }
}
